<?php
/**
 * Created by PhpStorm.
 * User: xiong <1099446868@qq.com>
 * DateTime: 2018/11/1
 * TIME: 17:31
 */

namespace app\lib\exception;

use think\Exception;
use think\exception\Handle;
use think\facade\Request;

/**TODO 自定义全局异常处理类
 * Class ParameterException
 * @package app\lib\exception
 * @userd 若要使用本类，需要先将app.php中的exception_handler换成本类
 */
class ExceptionHandler extends Handle {

    private $code;
    private $msg;
    private $errorCode;

    //这个方法会覆盖系统本身的异常处理
    public function render(\Exception $e){
        //如果开启了调试模式，由服务器内部错误的异常直接返回到客户端，否则不
        if($e instanceof BaseException){
            //如果是自定义的异常
            $this->code = $e->code;
            $this->msg = $e->msg;
            $this->errorCode = $e->errorCode;
        }else{
            $this->code = 500;
            $this->msg = '服务器内部错误';
            $this->errorCode = 50000;
        }


        $request = Request::instance();
        $result = [
            'msg'=>$this->msg,
            'error_code'=>$this->errorCode,
            'request_url'=>$request->url()
        ];
        return json($result, $this->code);
    }


}